package Pages;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.Sprite;

import Const.GConfig;
import Core.Event;
import Core.GLives;
import Core.KEY;
import Core.SMSSender;
import Core.ScrollMe;
import Core.Slide;
import Core.TextInput;
import Core.Touch;
import Core.VirtualKEY;

public class IGP extends Slide { 
	boolean isDebug = false;
	
	class Info{
		String name; private int xName, wName, tName = 10;
		String urlDetail, urlDownload, urlHighScore;
		String sub; private String arrText[];
		int star, nDownload;
		Image icon = null; private String picon;
	}
	class Detail{
		Info info; int index = -1;
		private String sName[];
		private int itab; String tcat, tname;
		String desc; private String arrText[];
		Image img[] = null; private String pimg[];
		public void reset(){
			desc = ""; if(img == null) return;
			for(int i = 0; i < img.length; i++){
				img[i] = null;
				pimg[i] = "";
			}
			img = null;
			System.gc();
		}
	}
	class Download{
		int index = -1;
		String CuPhap;
		String DauSo;
		String note;
	}
	String hs[][] = null;
	//tab
	String tab[][] = null;
	int iTabfocus = 0, iTabpaint = 0, iTabCurr = -1;
	int wTab;
	// scale
	final short PER_PAGE = 8;
	final short KC = 10;
	final short DWHEI = 140;
	short TOP = 88;
	short HEI = 90;//120;
	short HBANNER = 48;
	short DWTOP = 0;
	final short HTAB = 32;
	final short DY = 10;
	final short HTEXT = 28;
	final short HDESCTEXT = 18;
	//Touch
	final short SK_LEFT = 0;
	final short SK_RIGHT = 1;
	final short SK_CENTER = 2;
	final short TB_BACK = 3;
	final short TB_NEXT = 4;
	final short SH_CLEAR = 5;
	final short SH_INPUT = 6;
	final short DW_GIVE = 7;
	//state
	final short MAIN = 0;
	final short DETAIL = 1;
	final short HIGHSCORE = 2;
	final short DOWNLOAD = 3;
	final short SEARCHING = 4;
	public short state = MAIN;
	short paintState = state;
	short backState;
	int bakup[][] = new int[5][2];
	//effect
	final short EF_NOTHING = -1;
	final short EF_SEARCH_OPEN = 0;
	final short EF_SEARCH_CLOSE = 1;
	final short EF_SEARCHING = 2;
	final short EF_RESIZE = 3;
	final short EF_EXIT = 6;
	int iStepLoading = 0, iStepListLoading = 0;
	int efSearch = 0;
	int efgap = 0;
	int efID = 0; 
	int efResize = 0;
	int efWaitLoading = 0;

	HTTP httpI[], http[];
	Event eMain = null, ekbClose = null, ekbSearch = null;
	ScrollMe list;
	Detail dt = null;
	Download dl = null;
	Dialog dlg = null;
	TextInput tsearch, tnumber;
	VirtualKEY vk;
	
	private Vector vecMain = null;
	private Vector vecSearch = null;
	private Vector vec = null; // fake
	private int totalGame=0, totalGameSearch=0, page=0;
	private Image imgStar1, imgStar0, imgDefault,imgLoading, imgTabnext, imgBackSS, imgButton, imgButtonS, imgBSearch, imgListLoading;
	private Image imgBanner, imgSearch, imgLine, imgHor, imgVer, imgBorder, imgIconBak, imgNext, imgBack, imgDialog, imgDel;
	private Image imgStarDetail, imgJamo, imgBackdt, imgLinedt;
	int xStar, nameWidth;
	int iIMG_lst = 0, iIMG_dt = 0;
	int ifocus = 0, ifocusBak = 0;
	String strWarning = "", strSearch;
	String arrWar[] = null;
	boolean isLoading = false;
	boolean isSearch = false;
	boolean isSearching = false;
	boolean isVKclickIN = false;
	boolean isGive = false;
	
	// ---- EVENT -----
	
	public void init() {
//		GLives.isTouchable = false;
		int a=Connector.READ;
		setGameSize(GLives.ScreenWidth, GLives.ScreenHeight, 0);
		
		httpI = new HTTP[2]; for(int i = 0; i < 2; i++) httpI[i] = new HTTP();
		http = new HTTP[5]; for(int i = 0; i < 5; i++) http[i] = new HTTP();
		dt = new Detail();
		dl = new Download();
		dlg = new Dialog();
		vecMain = new Vector();
		vecSearch = new Vector();
		vec = vecMain;
		
		try {
			imgDefault = Image.createImage("/IGP/default.png");
			imgStar0 = Image.createImage("/IGP/starBlack.png");
			imgStar1 = Image.createImage("/IGP/starRed.png");
			imgLoading = Image.createImage("/IGP/loading.png");
			imgIconBak = Image.createImage("/IGP/iconback.png");
			imgNext = Image.createImage("/IGP/next.png");
			imgLine = Image.createImage("/IGP/line.png");
			imgTabnext = Image.createImage("/IGP/tabnext.png");
			imgBackSS = Image.createImage("/IGP/backSS.png");
			imgButton = Image.createImage("/IGP/button1.png");
			imgButtonS = Image.createImage("/IGP/button.png");
			imgBSearch = Image.createImage("/IGP/search.png");
			imgBack = Image.createImage("/IGP/back.png");
			imgDialog = Image.createImage("/IGP/bframe.png");
			imgListLoading = Image.createImage("/IGP/list_loading.png");
			imgDel = Image.createImage("/IGP/del.png");
			imgStarDetail = Image.createImage("/IGP/starDetail.png");
			imgJamo = Image.createImage("/IGP/jamo.png");
			imgBackdt = Image.createImage("/IGP/back_btn.png");
			imgLinedt = Image.createImage("/IGP/line1.png");
			
		} catch (Exception e) {}
		
		list = new ScrollMe(inW, 0, 2);
		list.setList(eMain = new Event(){
			public void action() {
				boolean isLoadmore = false;
				if(!isSearching){
					if(vecMain.size() < totalGame) isLoadmore = true;
				} else if(vecSearch.size() < totalGameSearch) isLoadmore = true;
				if(isLoadmore){
					addDebug("--------------- Load more...");
					KEY.resetKey(KEY.DOWN);
					sendRequest(MAIN, 1);
				}
			}
		});
		
		vk = new VirtualKEY();
		vk.setCommand("Cancel", "Space", "Search");
		vk.setCommand(ekbClose = new Event(){
			public void action(){
				addDebug("Close KB");
				showSearch(false);
			}
		}, ekbSearch = new Event(){
			public void action(){
				addDebug("Search!");
				if(tsearch.getText().trim().length() == 0)
					return;
				showSearching(true);
				vecSearch.removeAllElements();
				list.viewH = 0;
				list.goTo(0, 0);
				vk.hideKeyboard();
				registerTouch();
				strSearch = "... vui lòng đợi ...";
				sendRequest(MAIN, 1);
				efID = EF_SEARCHING; efgap = (inW>>1) - 5; 
			}
		});
		tsearch = new TextInput("", 120, TextInput.INPUT_TYPE_ANY);
		tnumber = new TextInput("", 11, TextInput.INPUT_TYPE_NUMERIC);
		GLives.ins.startTextInput();
		
		resizeImage();
		showSearch(false);
		sendRequest(MAIN, 1);
		correctOffset();
	}
	
	public void destroy() {
		(new Thread(){
			public void run(){
				for(int i = 0; i < 2; i++)
					httpI[i].cancel();
				for(int i = 0; i < 5; i++)
					http[i].cancel();
			}
		}).start();
		
		eMain = null; ekbClose = null; ekbSearch = null;
		list.destroy();
		list = null;
		dt = null;
		dl = null;
		dlg = null;
		tsearch = null;
		tnumber = null;
		vecMain = null;
		vecSearch = null;
		imgStar1=null;imgStar0=null;imgDefault=null;imgLoading=null;imgTabnext=null;
		imgBackSS=null;imgButton=null;imgButtonS=null;imgBSearch=null;imgListLoading=null;
		imgBanner=null;imgSearch=null;imgLine=null;imgHor=null;imgVer=null;imgBorder=null;
		imgIconBak=null;imgNext=null;imgBack=null;imgDialog=null;imgDel=null;
		imgStarDetail=null;imgJamo=null;imgBackdt=null;imgLinedt=null;
	}
	
	public void onResize() {
		efID = EF_RESIZE;
		efResize = 0;
	}
	
	private void onResizeW(){
		setGameSize(GLives.ScreenWidth, GLives.ScreenHeight, 0);
		resizeImage();
		correctOffset();
		if(!isLoading){
			if(state == MAIN){
				for(int k = 0; k < vec.size(); k++){
					Info in = (Info)vec.elementAt(k);
					resizeSubText(in);
				}
			} else if(state == DETAIL){
				resizeDetailText();
			}
		}
		dlg.rezise();
	}
	
	private void correctOffset(){
		switch(state){
		case MAIN:
		{
			list.viewW = inW;
			list.setViewer(inX, TOP, inW, inH - TOP - KC);
			
			wTab = (inW - 4)/3;
			xStar = inX + inW - KC - 5;

			nameWidth = xStar - 5*(imgStar0.getWidth() + 5) - inX - 18;
			
			tsearch.setBound(inX + 25, inY + imgBanner.getHeight() + 5, inW - 55, 25, 0x1a2578);
			vk.setBound(-1, -1, -1, GLives.ScreenHeight < 360 ? 185 : 252, GLives.ScreenWidth <= 360 ? (byte)2 : (byte)0);
			break;
		}
		case HIGHSCORE:
		{
			list.viewW = inW - 20;
			list.setViewer(inX + 10,  inY + 85, inW - 20, inH - 85 - 43);
			break;
		}
		case DETAIL:
		{
			list.viewW = inW;
			list.setViewer(inX, inY, inW, inH - 30);
			resizeDetailBaseText();
			break;
		}
		case DOWNLOAD:
		{
			tnumber.setBound((GLives.ScreenWidth>>1) - 58, inY + inH - 32, 116, 25, 0x1a2578);
			vk.setBound(-1, -30, -1, GLives.ScreenHeight < 360 ? 185 : 252, (byte)3);
			break;
		}
		}
	}
	
	private void correctHList(short subState){
		if(subState == MAIN){
			list.viewH = vec.size()*(HEI + DY) + (http[isSearching ? SEARCHING : MAIN].isWaiting ? list.HLOADING : 0);
		} else
		if(subState == DETAIL){
			list.viewH =  imgBanner.getHeight() + imgIconBak.getHeight() + 80 + HTAB + HDESCTEXT*dt.arrText.length + KC;
			if(dt.img != null)
			for(int i = 0; i < dt.img.length; i++)
				list.viewH += dt.img[i].getHeight() + KC + 30;
		} else
		if(subState == HIGHSCORE){
			if(hs != null) list.viewH = hs.length*HTEXT;
			else list.viewH = 0;
		}
	}
	
	private void resizeImage(){
		try {
			// LOGO
			Image logo = Image.createImage("/IGP/logo.png");
			Image bgk = Image.createImage("/IGP/bkg.png");
			imgBanner = Image.createImage(inW, logo.getHeight());
			Graphics g = imgBanner.getGraphics();
			g.drawImage(logo, 0, 0, 0);
			for(int i = logo.getWidth(); i < inW; i+= bgk.getWidth())
				g.drawImage(bgk, i, 0, 0);

			switch(state){
			case MAIN:
				// SEARCH
				Image t1 = Image.createImage("/IGP/search_L.png");
				Image t2 = Image.createImage("/IGP/search_C.png");
				Image t3 = Image.createImage("/IGP/search_R.png");
				imgSearch = Image.createImage(inW - 10, t1.getHeight());
				g = imgSearch.getGraphics();
				g.drawImage(t1, 0, 0, 0);
				for(int i = t1.getWidth(); i < imgSearch.getWidth() - 15; i+= t2.getWidth())
					g.drawImage(t2, i, 0, 0);
				g.drawImage(t3, imgSearch.getWidth(), 0, Graphics.RIGHT|Graphics.TOP);
				// BORDER
				imgBorder = Image.createImage("/IGP/border.png");
				imgHor = Image.createImage(inW - 2*KC, 3);
				Graphics gH = imgHor.getGraphics();
				for(int x = 0; x < imgHor.getWidth(); x+= 3)
					gH.drawRegion(imgBorder, 6, 0, 3, 3, 0, x, 0, 0);
				imgVer = Image.createImage(3, HEI);
				Graphics gV = imgVer.getGraphics();
				for(int y = 0; y < imgVer.getHeight(); y+= 3)
					gV.drawRegion(imgBorder, 6, 3, 3, 3, 0, 0, y, 0);
				
				t1 = null;
				t2 = null;
				t3 = null;
			}
			logo = null;
			bgk = null;
		}
		catch( Exception e){
		}
	}
	
	public void touchDrag(int x, int y) {
		if(vk.isShow()){
			vk.pointer(x, y);
		} else {
			list.move(x, y);
			if(y > GLives.ScreenHeight - KC)
				Touch.isPressed = false;
		}
	}
	public void touchDown(int ID, int x, int y) {
		if(isSearch) tsearch.updateTouch(x, y);
		else if(isGive) tnumber.updateTouch(x, y);
		if(vk.isShow()){
			isVKclickIN = vk.pointer(x, y);
			if(!isVKclickIN){
				if(Touch.IDdown == SH_CLEAR || Touch.IDdown == SH_INPUT) // || Touch.IDdown == DW_GIVE
					isVKclickIN = true;
				else {
					vk.hideKeyboard();
					registerTouch();
				}
			}
			list.isActive = false;
		}
		else list.moveStart(x, y);
	}
	public void touchUp(int ID, int x, int y) {
		if(vk.isShow()){
			vk.pointer_Released(x, y);
		}
	}
	public void touchUp(int ID, int x, int y, int dragTime, int xBegin, int yBegin) {
		list.moveFinish(ID, x, y, dragTime, xBegin, yBegin);
	}
	
	public void Click(int ID, int x, int y) {
		if(dlg.iFrameCnt!=0){
			dlg.hide();
			return;
		}
		if(efID == EF_EXIT) return;
		if(ID == SK_RIGHT) onkeyDown(KEY.RIGHT_SOFTKEY);
		else if(ID == SK_LEFT) onkeyDown(KEY.LEFT_SOFTKEY);
		else if(ID == SK_CENTER) onkeyDown(KEY.OK); else
		switch(state){
		case MAIN:
		{
			if(isSearch){
				if(ID == SH_CLEAR){
					tsearch.setText("");
					tsearch.setOffset();
				} else if(ID == SH_INPUT){
					if(!vk.isShow()){
						vk.showKeyboard(-1, -1, true);
						registerTouch();
					}
					tsearch.setFocus();
				} else if(vk.isShow() || (!vk.isShow() && !isVKclickIN)){
					isVKclickIN = true;
					return;
				}
				isVKclickIN = true;
			}
			if(ID == TB_BACK){
				if(iTabpaint > 0){ iTabpaint--; return;}
				else ID = Touch.NOTHING;
			}else if(ID == TB_NEXT){
				if(iTabpaint + 2 < tab.length - 1){iTabpaint++; return;}
				else ID = Touch.NOTHING;
			}
			if(ID == Touch.NOTHING){
				if(!list.isInner(y, 0)){
					if(y > HBANNER && y < HBANNER + HTAB){
						int t = x/wTab; if(t > 2) t = 2;
						changeTab(iTabpaint, iTabpaint + t);
					}
					return;
				}
				y = list.gotYin(y) - 3;
				int index = y/(HEI + DY);
				if(index < 0 || index >= vec.size())
					return;
				if(x > inX + KC && y > index*(HEI+DY) && x < inX + inW - KC && y < index*(HEI+DY) + HEI){
					if(this.ifocus == index){
						sendRequest(DETAIL, index);
						return;
					}
					this.ifocus = index;
				}
			}
			break;
		}
		case DETAIL:
		{
			int t = list.getY() + imgBanner.getHeight() + 5; 
			if(x > inX + 2 && y > t && x < inX + dt.itab && y < t + HTAB)
				onkeyDown(KEY.RIGHT_SOFTKEY);
			break;
		}
		case DOWNLOAD:
			if(ID == DW_GIVE){
				if(!vk.isShow()) vk.showKeyboard(-1, -30, true);
			}
			break;
		}
	}
	
	public void update() {
		//float
		list.update();
		dlg.update();
		
		//effect
		if(isLoading){
			iStepLoading++; if(iStepLoading >= 14*3) iStepLoading = 0;
		}
		if (list.isLoading){
			iStepListLoading++; if(iStepListLoading >= 15) iStepListLoading = 0;
		}
		if(isSearch){
			efSearch++; if(efSearch >= 9) efSearch = 0;
		}
		if(efWaitLoading > 0){
			efWaitLoading--;
			if(efWaitLoading == 0) changeTab();
		}
		if(efID != EF_NOTHING)
		switch(efID){
		case EF_SEARCH_OPEN:
			if(HBANNER < 80){
				efgap = (80 - HBANNER + 2) >> 1;
				HBANNER += (short)efgap;
				TOP += (short)efgap;
				list.setViewer(inX, TOP, inW, inH - TOP - 5);
			} else{
				registerTouch();
				efID = EF_NOTHING;
			}
			break;
		case EF_SEARCH_CLOSE:
			if(HBANNER > 48){
				efgap = (HBANNER - 48 + 2) >> 1;
				HBANNER -= (short)efgap;
				TOP -= (short)efgap;
				list.setViewer(inX, TOP, inW, inH - TOP - 5);
			} else{
				registerTouch();
				efID = EF_NOTHING;
			}
			break;
		case EF_SEARCHING:
			if(efgap > 0) efgap -= (efgap + 2) >> 1;
			else efID = EF_NOTHING;
			break;
		case EF_RESIZE:
			if(efResize < 12){
				efResize++;
				if(efResize == 12){
					efID = EF_NOTHING;
					onResizeW();
				}
			}
			break;
		case EF_EXIT:
			if(efgap < GLives.ScreenWidth)
				 efgap += (GLives.ScreenWidth + 12 - efgap + 8) >> 3;
			else{
				changeState(State.MAIN_MENU);
				return;
			}
			break;
		}
		
		// game
		if(state == MAIN){
			if(isSearch) tsearch.update();
			
			for(int i = 0; i < vec.size(); i++){
				Info in = (Info)vec.elementAt(i);
				if(in.wName > nameWidth){
					if(in.tName > 0){
						in.tName--; if(in.tName == 12) in.xName = 0;
					} else if(in.xName + in.wName > nameWidth) in.xName--;
					else in.tName=24;
				}
			}
			
			if(KEY.LoopCount(KEY.DOWN) > 5 && KEY.LoopCount(KEY.DOWN) % 2 == 0){
				if(ifocus < vec.size()-1) ifocus++;
				list.select(ifocus*(HEI + DY), HEI + DY);
			}
			else if(KEY.LoopCount(KEY.UP) > 5 && KEY.LoopCount(KEY.UP) % 2 == 0){
				if(ifocus > 0) ifocus--;
				list.select(ifocus*(HEI + DY), HEI + DY);
			}
		} else if(state == DOWNLOAD){
			if(isGive) tnumber.update();
		} else if(KEY.isPressed(KEY.DOWN))
			list.scrollDown();
		else if(KEY.isPressed(KEY.UP))
			list.scrollUp();
	}
	
	public void paint(Graphics g) {
		// fill nen Black
		g.setColor(0);//g.getDisplayColor(0x404c58)
		g.fillRect(0, 0, GLives.ScreenWidth, GLives.ScreenHeight);
		//paint GameState
		switch(paintState){
		case MAIN:
		{
			// fill background List
			g.setColor(0x404c58);
			g.fillRect(inX+1, inY + HBANNER, inW-2, inH-HBANNER-1);
			// draw Banner
			g.drawImage(imgBanner, inX, inY, 0);
			//Search
			if(isSearch){ 
				g.drawImage(imgSearch, inX + (inW>>1), inY + imgBanner.getHeight() + 5, Graphics.HCENTER|Graphics.TOP);
				tsearch.paint(g);
			}
			
			//draw tab
			g.setColor(0x2e3c45);
			if(tab == null){
				g.setColor(0xFFFFFF);
				g.fillRect(inX+1, HBANNER, inW-2, inH-HBANNER-1);
				if(isLoading) paintLoading(g);
			} else if(isSearching){
				g.fillRect(inX + efgap + 2, HBANNER + 1, inW - (efgap<<1) - 4, HTAB - 1);
				drawString(g, strSearch, GLives.ScreenWidth>>1, HBANNER + 7, 2, 0xa1d733);
			} else {
				g.fillRect(inX + 2, HBANNER, inW - 4, HTAB);
				if(iTabfocus >= iTabpaint && iTabfocus - iTabpaint <= 2){
					g.setColor(0x404c58);
					g.fillRect(inX + 2 + wTab*(iTabfocus - iTabpaint), HBANNER, wTab + 1, HTAB);
				}
				g.setColor(0x536069); //59636c
				g.drawLine(inX + 2, HBANNER, inX + inW - 2, HBANNER);
				g.drawLine(inX + inW - 2, HBANNER, inX + inW - 2, HBANNER+HTAB-1);
				g.drawImage(imgLine, inX + wTab, HBANNER, 0);
				g.drawImage(imgLine, inX + 2*wTab, HBANNER, 0);
				if(iTabpaint > 0) g.drawRegion(imgTabnext, 0, 0, 4, 6, 0, inX + 5, HBANNER + (HTAB>>1), Graphics.VCENTER|Graphics.LEFT);
				if(iTabpaint + 2 < tab.length - 1) g.drawRegion(imgTabnext, 4, 0, 4, 6, 0, inX + inW - 5, HBANNER + (HTAB>>1), Graphics.VCENTER|Graphics.RIGHT);
				
				for(int i = iTabpaint; i < iTabpaint + 3; i++){
					drawString(g, tab[i][2], inX + (i-iTabpaint)*wTab + (wTab>>1) + 1, HBANNER + 7 + 1, 2, 0x999999);
					drawString(g, tab[i][2], inX + (i-iTabpaint)*wTab + (wTab>>1), HBANNER + 7, 2, i == iTabfocus ? 0xB4FB25 : 0xFFFFFF);
				}
			}

			list.setClip(g);
			if(tab != null && vec.isEmpty()){
				paintBorder(g, inX + KC, list.getTop() + 3, inW - 2*KC, inH - list.getTop() - KC - 5, 0xFFFFFF);
				g.setClip(g.getClipX(), g.getClipY() + 10, g.getClipWidth(), g.getClipHeight() - 15);
				if(list.isLoading)
					//draw the first loading
					paintLoading(g);
				else {
					//draw reload (disconnect)
					if(arrWar != null)
						for(int i = 0; i < arrWar.length; i++)
							drawString(g, arrWar[i], GLives.ScreenWidth>>1, list.getY() + 20 + i*20, 2, 0x404c58 );
				}
			} else {
				//draw list Item
				for(int k = 0, top = list.getY() + 3; k < vec.size(); k++, top += HEI + DY){
					
					if(!list.isInner(top, HEI))
						continue;
					
					//border
					g.drawImage(imgHor, inX + KC + 3, top - 3, 0);
					g.drawRegion(imgHor, 0, 0, imgHor.getWidth(), imgHor.getHeight(), Sprite.TRANS_ROT180, inX + KC + 3, top + HEI + 1, 0);
					g.drawImage(imgVer, inX + KC - 3, top + 3, 0);
					g.drawRegion(imgVer, 0, 0, imgVer.getWidth(), imgVer.getHeight(), Sprite.TRANS_ROT180, inX + inW - KC + 1, top + 3, 0);
					g.drawRegion(imgBorder, 0, 0, 6, 6, 0, inX + KC - 3, top - 3, 0);
					g.drawRegion(imgBorder, 0, 0, 6, 6, Sprite.TRANS_ROT270, inX + KC - 3, top + HEI - 2, 0);
					g.drawRegion(imgBorder, 0, 0, 6, 6, Sprite.TRANS_ROT90, inX + inW - KC - 2, top - 3, 0);
					g.drawRegion(imgBorder, 0, 0, 6, 6, Sprite.TRANS_ROT180, inX + inW - KC - 2, top + HEI - 2, 0);
					if(ifocus == k){
						g.setColor(0x6A869E);
						g.fillRect( inX + KC, top, inW - 2*KC, HEI);
						g.setColor(0xB5FC26);
						g.drawRect( inX + KC, top, inW - 2*KC, HEI);
					} else {
						g.setColor(0xFFFFFF);
						g.fillRect( inX + KC, top, inW - 2*KC, HEI);
						g.setColor(0x6A869E);
						g.drawRect( inX + KC, top, inW - 2*KC, HEI);
					}
					
					Info in = (Info)vec.elementAt(k);
					//game name
					g.setClip(inX + KC + 8, g.getClipY(), nameWidth, g.getClipHeight());
					drawStringBold(g, in.name, inX + KC + 8 + in.xName, top + 7, 0, 0x5B7D98);// ifocus == k ? 0xFFFFFF : 0x5B7D98);
					list.setClip(g);
					//star
					for(int i = 0; i < 5; i++)
						g.drawImage(imgStar0, xStar - i*(imgStar0.getWidth() + 5), top + 5, Graphics.TOP|Graphics.RIGHT);
					for(int i = 0; i < in.star; i++)
						g.drawImage(imgStar1, xStar - i*(imgStar0.getWidth() + 5), top + 5, Graphics.TOP|Graphics.RIGHT);
					//image game
					g.setColor(0xCDCDCD);
					g.fillRect(inX + KC + 10, top + 30, 48, 48);
					list.setClip(g, inX + KC + 10, top + 30, 48, 48);
					g.drawImage(in.icon, inX + KC + 10 + 24, top + 30 + 24, Graphics.HCENTER|Graphics.VCENTER);
					list.setClip(g);
					g.drawImage(imgIconBak, inX + KC + 4, top + 23, 0);
					//sub-info;
					if(in.arrText != null){
						int n = in.arrText.length; if(n > 3) n = 3; 
						for(int i = 0; i < n; i++)
							drawString(g, in.arrText[i], inX + KC + imgIconBak.getWidth() + 10, top + 30 + i*16, 0, ifocus == k ? 0xFFFFFF :0x0);
					}
					//next
					g.drawRegion(imgNext, ifocus == k ? 8 : 0, 0, 8, 19, 0, inX + inW - KC - 5, top + 20 + ((HEI-20)>>1), Graphics.VCENTER | Graphics.RIGHT);
				}
				//draw loading new Item
				if(list.isLoading && list.viewH > 0){
					int top = list.getY() + list.viewH - list.HLOADING;
					paintBorder(g, inX + KC, top, inW - 2*KC, list.HLOADING, 0xFFFFFF);
					g.drawRegion(imgListLoading, ((iStepListLoading/3)%5)*16, 0, 16, 11, 0, (GLives.ScreenWidth>>1) - 40, top + (list.HLOADING>>1), Graphics.HCENTER|Graphics.VCENTER);
					drawString(g, "loading - - -", (GLives.ScreenWidth>>1) + 10, top + 8, 2, 0x5B7D98);
				}
			}
			resetClip(g);
			vk.paint(g);
			break;
		}
		case HIGHSCORE:
		{
			g.setColor(0x404c58);
			g.fillRect(inX, inY, inW, inH);
			
			int t = inY + 7;
			paintBorder(g, inX + 5, t, inW - 10, inY + inH - t - 5, 0xDEDEDE);
			g.drawImage(imgJamo, GLives.ScreenWidth>>1, t + 6, Graphics.HCENTER|Graphics.TOP);
			t += 25;
			g.setColor(0xFFFFFF);
			g.fillRoundRect(inX + 10, t + 17, inW - 20, inH - t - 50, 20, 20);
			g.setColor(0xCCCCCC);
			g.drawRoundRect(inX + 10, t + 17, inW - 20, inH - t - 50, 20, 20);
			g.setColor(0xFFFFFF);
			g.fillRoundRect((GLives.ScreenWidth>>1) - 40, t + 10, 80, 20, 16, 16);
			g.setColor(0xCCCCCC);
			g.drawRoundRect((GLives.ScreenWidth>>1) - 40, t + 10, 80, 20, 16, 16);
			drawStringBold(g, "ĐIỂM CAO", GLives.ScreenWidth>>1, t + 13, 2, 0x727272);
			
			if(isLoading) {paintLoading(g); break;};
			
			drawStringBold(g, "Hạng", inX + 20, t + 32, 0, 0x6A869E);
			drawStringBold(g, "Tên", inX + 60, t + 32, 0, 0x6A869E);
			drawStringBold(g, "Điểm", inX + inW - 15, t + 32, 1, 0x6A869E);
			
			list.setClip(g);
			if(hs == null){
				//g.setColor(0xEEEEEE);
				//g.drawLine(inX + 20, t + 50, inX + inW - 20, t + 50);
				drawString(g, strWarning, GLives.ScreenWidth>>1, list.getY() + ((GLives.ScreenHeight-list.getY()-50)>>1), 2, 0xAAAAAA);
			} else
			for(int k = 0, top = list.getY() + ((HTEXT - GLives.ins.bmf_bold.getHeight())>>1); k < hs.length; k++, top += HTEXT){
				
				if(!list.isInner(top - ((HTEXT - GLives.ins.bmf_bold.getHeight())>>1), HTEXT))
					continue;
				
				g.setColor(0xEEEEEE);
				g.drawRect(inX, top - ((HTEXT - GLives.ins.bmf_bold.getHeight())>>1) + 2, inW, HTEXT - 4);
				
				drawString(g, hs[k][0], inX + 45, top, 1, 0xAAAAAA);
				drawString(g, hs[k][1], inX + 60, top, 0, 0x555555);
				drawString(g, hs[k][2], inX + inW - 15, top, 1, 0);//0xFF0011);
			}
			break;
		}
		case DETAIL:
		{
			int t = list.getY();
			// fill nen Black
			g.setColor(0);
			g.fillRect(0, 0, GLives.ScreenWidth, GLives.ScreenHeight);
			// draw Banner
			g.drawImage(imgBanner, inX, t, 0);
			t += imgBanner.getHeight() + 5;
			// fill background List
			g.setColor(0x404c58);
			g.fillRect(inX+1, t , inW-2, inH - 1 - t);
			//path
			g.setColor(0x2e3c45);
			g.fillRect(inX + 2, t , dt.itab-2, HTAB);
			g.setColor(0x536069); //59636c
			g.drawLine(inX + 2, t, inX + inW - 2, t);
			g.drawLine(inX + inW - 2, t, inX + inW - 2, t+HTAB-1);
			g.drawImage(imgLinedt, inX + dt.itab, t, 0);
			g.drawImage(imgBackdt, inX+5, t + (HTAB>>1), Graphics.LEFT|Graphics.VCENTER);
			drawString(g, dt.tcat, inX + 25, t + 8, 0, 0xFFFFFF);
			drawString(g, dt.tname, dt.itab + 10, t + 8, 0, 0xB4FB25);
			// body
			t += HTAB + 2;
			int lT = (GLives.ScreenHeight <= 220 ? 5 : KC);
			paintBorder(g, inX + lT, t+5, inW - 2*lT, inY + inH - t - 10, 0xFFFFFF);
			
			g.setClip(inX, inY, inW, inH - 30);
			
			// icon
			g.setColor(0xCDCDCD);
			g.fillRect(inX + 20, t + 15, 48, 48);
			list.setClip(g, inX + 20, t + 15, 48, 48);
			g.drawImage(dt.info.icon, inX + 24 + 20, t + 15 + 24, Graphics.HCENTER|Graphics.VCENTER);
			list.setClip(g);
			g.drawImage(imgIconBak, inX + 55 + 20, t + 8, Graphics.RIGHT|Graphics.TOP);
			// name
			lT = inX + imgIconBak.getWidth() + (GLives.ScreenHeight <= 220 ? 20 : 25);
			if(dt.sName != null){
			t = t + (dt.sName.length == 1 ? 15 : 12);
			for(int i = 0; i < dt.sName.length; i++, t+= 17)
				drawStringBold(g, dt.sName[i], lT, t, 0, 0x5b7f99);
			} else t+= 12;
			//star
			for(int i = 0; i < 5; i++)
				g.drawRegion(imgStarDetail, 14, 0, 14, 12, 0, lT + i*(14), t, Graphics.TOP|Graphics.LEFT);
			for(int i = 0; i < dt.info.star; i++)
				g.drawRegion(imgStarDetail,  0, 0, 14, 12, 0, lT + i*(14), t, Graphics.TOP|Graphics.LEFT);
			t+=15;
			// count
			drawString(g, "Lượt tải: ", lT, t, 0, 0x404c58);
			drawString(g, "" + dt.info.nDownload, lT + 50, t, 0, 0x404c58);

			t+= 30;
			
			if(isLoading && state == DETAIL) {paintLoading(g); break;};
			
			drawStringBold(g, "Giới thiệu", inX + 2*KC, t, 0, 0x404e59);
			t += GLives.ins.bmf_bold.getHeight() + 10;
			if(dt.arrText != null)
			for(int i = 0; i < dt.arrText.length; i++, t += HDESCTEXT){
				if(list.isInner(t, HDESCTEXT))
					drawString(g, dt.arrText[i], inX + 2*KC, t, 0, 0x0);
			}
			t += KC;
			if(dt.img != null){
				drawStringBold(g, "Hình ảnh", inX + 2*KC, t, 0, 0x404e59);
				t += GLives.ins.bmf_bold.getHeight() + KC;
				for(int i = 0; i < dt.img.length; t+= dt.img[i].getHeight() + 30 + KC, i++){
					if(list.isInner(t ,dt.img[i].getHeight() + 30))
						paintImageDesc(g, dt.img[i], t);
				}
			}
			break;
		}
		}
		if(state == DOWNLOAD)
		{
			resetClip(g);
			if(isGive) vk.paint(g);
		}
		paintCommand(g);
		dlg.drawMe(g);
		//list.drawDebug(g);
		//drawDebug(g); //TODO: debug
		
		if(efID == EF_EXIT){
			g.setColor(0);
			int ih = (GLives.ScreenHeight>>5);
			for(int i = 0; i < 32; i++){
				if(i % 2 == 0)  g.fillRect(i*(i>>2) - efgap, i*(ih + 1), i*i + 2*efgap, ih+1);
				else g.fillRect(GLives.ScreenWidth - efgap + i*(i - 18), i*(ih+1), efgap - 64, ih);
			}
		}
	}
	
	public void onkeyDown(int keyCode) {
		if(dlg.iFrameCnt!=0 && keyCode == KEY.OK){
			dlg.hide();
			return;
		}
		if(efID == EF_EXIT) return;
		switch (state) {
		case MAIN:
			// search
			if(!GLives.isTouchable && tab != null && keyCode >= KEY.NUM0 && keyCode <= KEY.NUM9){
				if(!isSearch){
					showSearch(true);
				} else if (!tsearch.isFocused) tsearch.setFocus();
			}
			if(keyCode == KEY.LEFT_SOFTKEY){
				if(tab != null) showSearch(!isSearch);
				break;
			}
			if(keyCode == KEY.RIGHT_SOFTKEY){
				if(tab == null || !isSearch || (!isSearching && ((tsearch.isFocused && GLives.isTouchable && !vk.isShow()) || (!tsearch.isFocused && !GLives.isTouchable)))){
					System.out.println("-> Thoat (Exit)");
					efID = EF_EXIT; efgap = 0;
					break;
				} else if(isSearch && tsearch.isFocused && GLives.isTouchable && vk.isShow()){
					ekbSearch.action();
					break;
				} else if(isSearching && (GLives.isTouchable || (!GLives.isTouchable && !tsearch.isFocused))){
					showSearching(false);
					break;
				}
			}
			
			if(tab == null) return;
			
			if(isSearch && tsearch.isFocused){
				tsearch.updateKeyPressed(keyCode);
				if(keyCode == KEY.OK && !GLives.isTouchable){
					ekbSearch.action();
					break;
				}
			}
			
			// base
			if(!vk.isShow()){
				if(keyCode == KEY.OK)
					sendRequest(DETAIL,this.ifocus);
				else if(keyCode == KEY.RIGHT && !isSearching){
					if(iTabfocus + 1 < tab.length){
						int itf = iTabfocus + 1;
						changeTab(itf == tab.length - 1 ? tab.length - 3 : itf-1, itf);
					}
				}
				else if(keyCode == KEY.LEFT && !isSearching){
					if(iTabfocus > 0){
						int itf = iTabfocus - 1;
						changeTab(itf == 0 ? 0 : itf-1, itf);
					}
				}
				//---
				if(KEY.isPressed(KEY.DOWN)){
					if(ifocus < vec.size()-1){
						ifocus++;
						list.select(ifocus*(HEI + DY), HEI + DY);
					}
				}
				else if(KEY.isPressed(KEY.UP)){
					if(ifocus > 0){
						ifocus--; 
						list.select(ifocus*(HEI + DY), HEI + DY);
					}else if(isSearch) 
						tsearch.setFocus();
				}
			}
			break;
		case DETAIL:
			if(keyCode == KEY.RIGHT_SOFTKEY)
				changeSub(MAIN);
			else if(keyCode == KEY.OK)
				sendRequest(HIGHSCORE, dt.index);
			else if(keyCode == KEY.LEFT_SOFTKEY)
				sendRequest(DOWNLOAD, dt.index);
			break;
		case HIGHSCORE:
			if(keyCode == KEY.OK)
				changeSub(backState);
			break;
		case DOWNLOAD:
			if(isGive){
				tnumber.updateKeyPressed(keyCode);
				tnumber.isFocused = true;
				if((GLives.isTouchable && keyCode == KEY.RIGHT_SOFTKEY) || (!GLives.isTouchable && keyCode == KEY.LEFT_SOFTKEY)){
					isGive = false;
					registerTouch();
				} else if((GLives.isTouchable && keyCode == KEY.LEFT_SOFTKEY) || keyCode == KEY.OK){
					if(sendSMS_toGiveFriend())
						isGive = false;				
				}
			} else {
				if(keyCode == KEY.RIGHT_SOFTKEY){
					changeSub(backState);}
				else if(keyCode == KEY.OK){
					isGive = true;
					vk.setCommand(null, null);
					vk.showKeyboard(-1, -30, true);
					tnumber.setText("");
					tnumber.setFocus();
					registerTouch();}
				else if(keyCode == KEY.LEFT_SOFTKEY){
					sendSMS_toDownload();
				}
			}
			break;
		}
	}
	
	public void registerTouch() {
		Touch.releaseTouchArea();
		if(state == MAIN){
			if(isSearch){
				Touch.addTouchArea(SH_CLEAR, inX + inW - 40, imgBanner.getHeight(), 50, imgSearch.getHeight()+10);
				Touch.addTouchArea(SH_INPUT, tsearch.x - 10, tsearch.y, tsearch.width, tsearch.height);
			}
			if(!vk.isShow()){
				if(tab != null)
				Touch.addTouchArea(SK_LEFT, inX, inY + inH  - 35, 50, 35);
				Touch.addTouchArea(SK_RIGHT, inX + inW - 50, inY + inH  - 35, 50, 35);
				if(!isSearching && tab != null){
					Touch.addTouchArea(TB_BACK, inX + 2, HBANNER, 15, HTAB);
					Touch.addTouchArea(TB_NEXT, inX + inW - 20, HBANNER, 15, HTAB);
				}
			}
		}
		else if(state == HIGHSCORE)
			Touch.addTouchArea(SK_CENTER,(GLives.ScreenWidth>>1) - 45, inY + inH  - 35, 90, 30);
		else if(state == DETAIL || state == DOWNLOAD){
			int mid = GLives.ScreenWidth>>1;
			if(state == DOWNLOAD && isGive){
				Touch.addTouchArea(SK_LEFT, mid - 130, inY + inH  - 35, 70, 30);
				Touch.addTouchArea(SK_RIGHT, mid + 60, inY + inH  - 35, 70, 30);
				Touch.addTouchArea(DW_GIVE, mid - 60, inY + inH  - 35, 120, 30);
			} else {
				Touch.addTouchArea(SK_LEFT, mid - 110, inY + inH  - 35, 70, 30);
				Touch.addTouchArea(SK_CENTER, mid - 40, inY + inH  - 35, 80, 30);
				Touch.addTouchArea(SK_RIGHT, mid + 40, inY + inH  - 35, 70, 30);
			}
		}
	}
	
	// ---- FUNCTION -----

	private void paintCommand(Graphics g){
		g.setClip(0, 0, GLives.ScreenWidth, GLives.ScreenHeight);
		if(state == MAIN){
			if(!vk.isShow()){
				if(!GLives.isTouchable && isSearch && tsearch.isFocused){
					g.drawImage(imgBack, inX, inY + inH + 2, Graphics.BOTTOM|Graphics.LEFT);
					g.drawRegion(imgBSearch, 0, 0, 44, 44, 0, GLives.ScreenWidth>>1, inY + inH, Graphics.BOTTOM|Graphics.HCENTER);
					g.drawImage(imgDel, inX + inW, inY + inH, Graphics.BOTTOM|Graphics.RIGHT);
				}
				else{
					if(tab != null)	g.drawRegion(imgBSearch, isSearch ? ((efSearch/3)%3)*44 : 0, 0, 44, 44, 0, inX, inY + inH, Graphics.BOTTOM|Graphics.LEFT);
					g.drawImage(imgBack, inX + inW, inY + inH + 2, Graphics.BOTTOM|Graphics.RIGHT);
				}
			}
		} else if(state == HIGHSCORE)
			paintButton(g, "Trở về", Touch.isPressed && Touch.IDdown == SK_CENTER , GLives.ScreenWidth>>1, inY + inH  - 29, 2, 2);
		else if(state == DOWNLOAD){
			int mid = GLives.ScreenWidth>>1;
			int htop = (GLives.ScreenHeight <= 220 ? 22 : 30);
			if(!isGive){
				paintButton(g, "< Tải", Touch.isPressed && Touch.IDdown == SK_LEFT, mid - 10, inY + inH  - htop, 1, 0);
				paintButton(g, "Hủy >", Touch.isPressed && Touch.IDdown == SK_RIGHT, mid + 11, inY + inH  - htop, 0, 1);
				paintButton(g, "Tặng bạn", Touch.isPressed && Touch.IDdown == SK_CENTER, mid, inY + inH  - htop, 2, 2);
			}else{
				paintButton(g, GLives.isTouchable ? "< Tặng" : "< Hủy", Touch.isPressed && Touch.IDdown == SK_LEFT, mid - 25, inY + inH  - htop, 1, 0);
				paintButton(g, GLives.isTouchable ? "Hủy >" : "Xóa >", Touch.isPressed && Touch.IDdown == SK_RIGHT, mid + 21, inY + inH  - htop, 0, 1);
				paintButton(g, "                                  ", Touch.isPressed && Touch.IDdown == SK_CENTER, mid, inY + inH  - htop, 2, 2);
				tnumber.paint(g);
			}
		} else if(state == DETAIL){
			int mid = GLives.ScreenWidth>>1;
			int htop = (GLives.ScreenHeight <= 220 ? 22 : 30);
			paintButton(g, "Tải", Touch.isPressed && Touch.IDdown == SK_LEFT, mid - 26, inY + inH  - htop, 1, 2);
			paintButton(g, "Trở về", Touch.isPressed && Touch.IDdown == SK_RIGHT, mid + 27, inY + inH  - htop, 0, 2);
			paintButton(g, "Điểm cao", Touch.isPressed && Touch.IDdown == SK_CENTER, mid, inY + inH  - htop, 2, 2);
		}
	}
	
	private void paintButton(Graphics g, String text, boolean isActive, int x, int y, int align, int alignText){
		int w = GLives.ins.bmf_normal.stringWidth(text) + 14;
		if(w < 80) w = 80;
		x = align==2 ? x-(w>>1) : align==1 ? x - w : x;
		g.drawRegion(isActive ? imgButtonS : imgButton, 0, 0, 8, 21, 0, x, y, 0);
		for(int i = x+8, kc = (w - 16) % 16; i < x + w - 8; i+= kc, kc = 16){
			g.drawRegion(isActive ? imgButtonS : imgButton, 8, 0, kc, 21, 0, i, y, 0);
		}
		g.drawRegion(isActive ? imgButtonS : imgButton, 28, 0, 8, 21, 0, x + w - 8, y, 0);
		drawString(g, text, alignText==2 ? x + (w>>1) : alignText==1 ? x + w - 5 : x + 5, y + 2, alignText, isActive ? 0xFFFFFF : 0x666666);
	}
	
	private void paintLoading(Graphics g){
		g.drawRegion(imgLoading, ((iStepLoading/3)%14)*32, 0, 32, 32, 0, GLives.ScreenWidth>>1, (GLives.ScreenHeight>>1) + 30, Graphics.HCENTER|Graphics.VCENTER);
	}
	private void paintImageDesc(Graphics g, Image img, int y){
		int x = (GLives.ScreenWidth - img.getWidth() - 30)>>1;
		int kc = img.getWidth() % 50;
		g.drawImage(img, x + 15, y + 15, 0);
		for(int i = x + 15; i < x + img.getWidth(); i +=kc, kc = 50){
			g.drawRegion(imgBackSS, 20, 0, kc, 15, 0, i, y, 0);
			g.drawRegion(imgBackSS, 20, imgBackSS.getHeight() - 15, kc, 15, 0, i, y + img.getHeight() + 15, 0);
		}
		kc = img.getHeight() % 50;
		for(int i = y + 15; i < y + img.getHeight(); i +=kc, kc = 50){
			g.drawRegion(imgBackSS, 0, 20, 15, kc, 0, x, i, 0);
			g.drawRegion(imgBackSS, imgBackSS.getWidth() - 15, 20, 15, kc, 0, x + img.getWidth() + 15, i, 0);
		}
		g.drawRegion(imgBackSS, 0, 0, 15, 15, 0, x, y, 0);
		g.drawRegion(imgBackSS, 0, imgBackSS.getHeight() - 15, 15, 15, 0, x, y + img.getHeight() + 15, 0);
		g.drawRegion(imgBackSS, imgBackSS.getWidth() - 15, 0, 15, 15, 0, x + img.getWidth() + 15, y, 0);
		g.drawRegion(imgBackSS, imgBackSS.getWidth() - 15, imgBackSS.getHeight() - 15, 15, 15, 0, x + img.getWidth() + 15, y + img.getHeight() + 15, 0);
	}
	
	private void paintBorder(Graphics g, int x, int y, int w, int h, int color){
		int G = imgBorder.getHeight();
		int WB = G>>1;
		int kc = (w - G + 1) % imgHor.getWidth();
		g.drawRegion(imgBorder, 0, 0, G, G, 0, x - WB, y - WB, 0);
		g.drawRegion(imgBorder, 0, 0, G, G, Sprite.TRANS_ROT270, x - WB, y + h - WB + 1, 0);
		for(int i = x + WB; i < x + w - WB; i +=kc, kc = imgHor.getWidth()){
			g.drawRegion(imgHor, 0, 0, kc, imgHor.getHeight(), Sprite.TRANS_NONE, i, y, Graphics.BOTTOM|Graphics.LEFT);
			g.drawRegion(imgHor, 0, 0, kc, imgHor.getHeight(), Sprite.TRANS_ROT180, i, y + h + 1, 0);
		}
		kc = (h - G + 1) % imgVer.getHeight();
		for(int i = y + WB; i < y + h - WB; i+=kc, kc=imgVer.getHeight()){
			g.drawRegion(imgVer, 0, 0, imgVer.getWidth(), kc, Sprite.TRANS_NONE, x, i, Graphics.RIGHT|Graphics.TOP);
			g.drawRegion(imgVer, 0, 0, imgVer.getWidth(), kc, Sprite.TRANS_ROT180, x + w + 1, i, 0);
		}
		g.drawRegion(imgBorder, 0, 0, G, G, Sprite.TRANS_ROT90, x + w - WB + 1, y - WB, 0);
		g.drawRegion(imgBorder, 0, 0, G, G, Sprite.TRANS_ROT180, x + w - WB + 1, y + h - WB + 1, 0);
		
		g.setColor(color);
		g.fillRect( x, y, w, h);
		g.setColor(0x6A869E);
		g.drawRect( x, y, w, h);
	}
	
	private void paintBFrame(Graphics g, int x, int y, int w, int h, Image imgborder, int connerW, int connerH, int leftW, int topH, int xH, int wH, int yV, int hV, boolean hasFill){
		int rw = (connerW - leftW); 
		int rh = (connerH - topH );
		g.drawRegion(imgborder, 0, 0, connerW, connerH, 0, x - leftW, y - topH, 0);
		g.drawRegion(imgborder, 0, imgborder.getHeight() - connerH, connerW, connerH, 0,x - leftW, y + h - rh + 1, 0);
		int kc = (w - 2*rw + 1) % wH;
		int temp = x + w - rw;
		for(int i = x + rw; i < temp; i +=kc, kc = wH){
			g.drawRegion(imgborder, xH, 0, kc, topH, Sprite.TRANS_NONE, i, y, Graphics.BOTTOM|Graphics.LEFT);
			g.drawRegion(imgborder, xH, 0, kc, topH, Sprite.TRANS_ROT180, i, y + h + 1, 0);
		}
		kc = (h - 2*rh + 1) % hV;
		temp = y + h - rh;
		for(int i = y + rh; i < temp; i+=kc, kc=hV){
			g.drawRegion(imgborder, 0, yV, leftW, kc, Sprite.TRANS_NONE, x, i, Graphics.RIGHT|Graphics.TOP);
			g.drawRegion(imgborder, 0, yV, leftW, kc, Sprite.TRANS_ROT180, x + w + 1, i, 0);
		}
		g.drawRegion(imgborder, imgborder.getWidth() - connerW, 0, connerW, connerH, 0, x + w - rw + 1, y - topH, 0);
		g.drawRegion(imgborder, imgborder.getWidth() - connerW, imgborder.getHeight() - connerH, connerW, connerH, 0, x + w - rw + 1, y + h - rh + 1, 0);
		if(hasFill){
			/** // Fill with inner Image 
//			int wB = imgborder.getWidth() - 2*connerW + 1;
//			int hB = imgborder.getHeight() - 2*connerH + 1;
//			for(int i = x; i < x+w; i +=wB){
//				for(int j = y; j < y+h; j+=hB){
//					g.drawRegion(imgborder, connerW, connerH, wB, hB, 0, i, j, 0);
//				}
//			} */
			g.setColor(0xEFF7EE);
			g.fillRect(x + rw, y, w - 2*rw + 1, rh);
			g.fillRect(x + rw, y + h - rh + 1, w - 2*rw + 1, rh);
			g.fillRect(x, y + rh, w + 1, h - 2*rh + 1);
		}
	}
	
	private void showSearch(boolean isShow){
		isSearch = isShow;
		if(isSearch){
			vk.setCommand(ekbClose, ekbSearch);
			vk.showKeyboard(-1, -1, true);
			tsearch.setText("");
			tsearch.setFocus();
		} else {
			vk.hideKeyboard();
			tsearch.isFocused = false;
			showSearching(false);
		}
		if(isSearch) efID = EF_SEARCH_OPEN;
		else efID = EF_SEARCH_CLOSE;
		Touch.releaseTouchArea();
	}
	
	private void showSearching(boolean isShow){
		if(isShow){
			isSearching = true;
			vec = vecSearch;
			ifocusBak = ifocus;
			deleteImage(vecSearch);
			bakup[SEARCHING][0] = list.getY();
			bakup[SEARCHING][1] = list.viewH;
			
			if(httpI[MAIN].isWaiting) httpI[MAIN].stop();
		} else{
			isSearching = false;
			vec = vecMain;
			ifocus = ifocusBak;
			deleteImage(vecSearch);
			if(list.isLoading) list.hideLoading();
			list.viewH = bakup[SEARCHING][1];
			list.setY(bakup[SEARCHING][0]);
			
			if(http[SEARCHING].isWaiting) http[SEARCHING].stop();
			if(httpI[MAIN].isWaiting) httpI[MAIN].stop();
			sendIMGrequest(MAIN, 0);
		}
	}
	
	private void changeTab(int pT, int fT){
		iTabpaint = pT;
		iTabfocus = fT;
		efWaitLoading = 10;
	}
	private void changeTab(){
		if(iTabCurr == iTabfocus){
			System.out.println("Trung tab! Khong load!");
			return;
		}
		iTabCurr = iTabfocus;
		page = 0;
		ifocus = 0;
		iIMG_lst = 0;
		dt.index = dl.index = -1;
		httpI[MAIN].stop();
		deleteImage(vec);
		vec.removeAllElements();
		list.viewH = 0;
		sendRequest(MAIN, 1);
	}
	
	private void changeSub(short state){
		if(state == DETAIL) changeSub(state, dt.index);
		else if(state == DOWNLOAD) changeSub(state, dl.index);
		else if(state == HIGHSCORE) changeSub(state, dt.index); // hsIndex
		else changeSub(MAIN, 0);
	}
	
	private boolean changeSub(short subState, int index){
		//Quyet dinh co Loading hay khong !
		isLoading = false;
		switch(subState){
		case MAIN:
		{
			if(index == 1){ // ep buot load moi
				isLoading = true;
				//TODO: huy ket noi cu !?
//				if(http[isSearching ? SEARCHING : MAIN].isWaiting) 
//					http[isSearching ? SEARCHING : MAIN].stop();
			} else if(isSearching){
				//int size = http[SEARCHING].param ; // vec size
				if(http[SEARCHING].isWaiting)
					isLoading = true;
			} else {
				int tID = (http[MAIN].param[0] >> 16)&0xFF; // tab ID
				int size = http[MAIN].param[0] & 0xFF ; // vecHttp size
				addDebug("tabFocus="+iTabfocus+" tabID="+tID+" size="+size+" vecMain.size()="+vecMain.size());
				if(iTabfocus == tID){
					if(http[MAIN].isWaiting)
						isLoading = true;
				} else isLoading = true;
			}
			break;
		}
		case DETAIL:
		{
			dt.index = index; dt.info = ((Info)vec.elementAt(index));
			if(index == http[DETAIL].param[0] && http[DETAIL].param[0]!=-1){
				if(http[DETAIL].isWaiting)
					isLoading = true;
				changeSubFunc(subState);
				return true;
			} else{
				//TODO: huy ket noi cu !?
//				if(http[DETAIL].isWaiting){
//					dlg.show_static("server đang bận! Vui lòng chờ giây lát!");
//					return true;
//				} else
				isLoading = true;
			}
			break;
		}
		case DOWNLOAD:
		{
			dl.index = index;
			// download luon loaing am tham
			if(index == http[DOWNLOAD].param[0] && http[DETAIL].param[0]!=-1){
				changeSubFunc(subState);
				return true;
			}
			break;
		}
		case HIGHSCORE:
			//TODO: huy ket noi cu !?
//			if(http[HIGHSCORE].isWaiting){
//				dlg.show_static("server đang bận! Vui lòng chờ giây lát!");
//				return true;
//			} else
			if(index == http[HIGHSCORE].param[0] && http[HIGHSCORE].param[0]!=-1){
				changeSubFunc(subState);
				return true;
			}
			isLoading = true; // luon luon load moi
			break;
		}
		
		changeSubFunc(subState);
		return false;
	}
	
	private void changeSubFunc(short state){
		addDebug("===ChangeSUB: "+state + " isLoading="+isLoading);
		bakup[this.state][0] = list.getY();
		bakup[this.state][1] = list.viewH; // du thua , ow
		
		backState = this.state;
		this.state = state;
		paintState = (state == DOWNLOAD ? backState : state);
		strWarning = "";
		
		correctOffset();
		registerTouch();
		
		// neu chi chuyen state binh thuong khong load data
		if(!isLoading && state != DOWNLOAD && backState != DOWNLOAD){
			addDebug("Correct ViewH ________________");
			correctHList(paintState);
			//list.viewH = bakup[state][1]; // this row is deleted!
			list.setY(bakup[state][0]);
		}
		if(isLoading && state != MAIN && state != DOWNLOAD){
			list.viewH = 0;
			list.getTo(0, 0);
		}
		
		list.setList(state == MAIN ? eMain : null);
	}
	
	private void deleteImage(Vector vec){
		for(int k = 0; k < vec.size(); k++){
			Info in = (Info)vec.elementAt(k);
			in.icon = null;
		}
		System.gc();
	}
	
	private void resizeSubText(Info in){
		in.arrText = GLives.ins.bmf_normal.splitStrInLine(in.sub, inW - 2*KC - 3*5 - imgIconBak.getWidth() - 15);
		if(in.arrText.length > 3) in.arrText[2] = in.arrText[2].substring(0, in.arrText[2].length() - 3) + "...";
	}
	private void resizeDetailText(){
		dt.arrText = GLives.ins.bmf_normal.splitStrInLine(dt.desc, inW - 4*KC-2);
		System.out.println("wwwwwwwwwwwwwwww 4");
		resizeDetailBaseText();
	}
	private void resizeDetailBaseText(){
		dt.sName = GLives.ins.bmf_bold.splitStrInLine(dt.info.name, inW - imgIconBak.getWidth() - (GLives.ScreenHeight <= 220 ? 30 : 50));
		dt.tcat = GLives.ins.bmf_normal.stringFixEtc(tab[iTabfocus][1], (inW>>1)-30);
		dt.itab = 30 + GLives.ins.bmf_normal.stringWidth(dt.tcat);
		dt.tname = GLives.ins.bmf_normal.stringFixEtc(dt.info.name, inW-dt.itab-15);
	}
	
//	public String URLEncode(String s)
//	{
//	        if (s!=null) {
//	            StringBuffer tmp = new StringBuffer();
//	            int i=0;
//	            try {
//	                while (true) {
//	                    int b = (int)s.charAt(i++);
//	                    if ((b>=0x30 && b<=0x39) || (b>=0x41 && b<=0x5A) || (b>=0x61 && b<=0x7A)) {
//	                        tmp.append((char)b);
//	                    }
//	                    else {
//	                        tmp.append("%");
//	                        if (b <= 0xf) tmp.append("0");
//	                        tmp.append(Integer.toHexString(b));
//	                    }
//	                }
//	            }
//	            catch (Exception e) {}
//	            return tmp.toString();
//	        }
//	        return null;
//	}
	
	public String URLEncode(String sUrl){
		StringBuffer urlOK = new StringBuffer();
		for(int i=0; i<sUrl.length(); i++){
			char ch=sUrl.charAt(i);
			switch(ch){
				case '<': urlOK.append("%3C"); break;
				case '>': urlOK.append("%3E"); break;
				case '/': urlOK.append("%2F"); break;
				case ' ': urlOK.append("%20"); break;
				case ':': urlOK.append("%3A"); break;
				case '-': urlOK.append("%2D"); break;
				default: urlOK.append(ch); break;
			}
		}
		return urlOK.toString();
	}
	
	private void sendIMGrequest(short stateID, int next){
//[Van] Debug
		if(isDebug) return;
		
		switch(stateID){
		case MAIN:
			for(iIMG_lst = next;iIMG_lst < vec.size(); iIMG_lst++){
				Info in = (Info)vec.elementAt(iIMG_lst);
				if(in.icon == imgDefault){
					httpI[MAIN].setImageURL(stateID, in.picon);
					break;
				}
			}
			break;
		case DETAIL:
			if(dt.img == null || next >= dt.img.length) return;
			httpI[DETAIL].setImageURL(stateID, dt.pimg[iIMG_dt = next]);
			break;
		}
	}
	public void getImageData(short stateID, byte[] dataget){
		switch(stateID){
		case MAIN:
			if(dataget != null && vec != null && iIMG_lst < vec.size())
				((Info)vec.elementAt(iIMG_lst)).icon = Image.createImage(dataget, 0, dataget.length);
			sendIMGrequest(MAIN, iIMG_lst + 1);
			break;
		case DETAIL:
			if(dataget != null && dt.img != null && iIMG_dt < dt.img.length)
				dt.img[iIMG_dt] = Image.createImage(dataget, 0, dataget.length);
			sendIMGrequest(DETAIL, iIMG_dt + 1);
			correctHList(DETAIL);
			break;
		}
	}
	private void sendRequest(short subState, int index){
		if(subState != MAIN && vec.isEmpty()) return;
		addDebug("=================sendRequest: "+subState);
		
		// before loading new state
		if(changeSub(subState, index))
			return;
		
//[Van] ------------------> Debug
		if(isDebug){
			switch(subState){
			case MAIN:
				if(tab == null) tab = new String[][]{{"0","TOP 25","TOP 25"}, {"1","GAME","GAME"}, {"2","APP","APP"}, {"3","WEB","WEB"}, {"4","OTHER","OTHER"}};
				
				String s = ""; list.showLoading();
				int num = 12; if(isSearching) num = 7;
				for(int i = 1; i <= num; i++){
					s += (char)21 + (isSearching ? tsearch.getText() : tab[iTabfocus][1]) + " demo 2011 (C) Jamo Studio " + i + ".0"+(char)20+"mid=<mid>"+(char)20+"mid=<mid>&id=<id2>"+(char)20+"mid=<mid>&id=<id2>"+(char)20+"a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a!!!"+(char)20+ (i%6) +(char)20+ "http://123.com/a.png";
				} getData(isSearching?SEARCHING:MAIN, "0 " + s.substring(1) + "\r\n" + num);
				break;
			case HIGHSCORE:
				String sH = "";
				hs = null;
				for(int i = 1; i <= 10; i++) sH +=(char)20 + "Tên của user " + i + "," + (i*10+3);
				getData(HIGHSCORE, "2 " + sH.substring(1));
				break;
			case DETAIL:
				dt.reset();
				dt.index = index; dt.info = ((Info)vec.elementAt(index));
				String s1 = "Game bắn tàu được mô phỏng theo game bắn xe tăng 2K7. Bạn đã sẵn sàng cho thử thách mới?\r\n";for(int i = 0; i < 1; i++)s1+=s1;
				getData(DETAIL, "1 " + "1234567"+(char)20+s1+(char)20+"http://farm6.static.flickr.com/5092/5539641108_3c85e406cf_m.jpg|http://farm5.static.flickr.com/4060/4392751794_d50d0dea2d_s.jpg");
				break;
			case DOWNLOAD:
				dl.index = index;
				dl.DauSo = dl.CuPhap = dl.note = "";
				getData(DOWNLOAD, "M:HSO 01"+(char)20+"8077");
				break;
			}
			return; // <------------------- return
		}
		
		// sending a request
		switch(subState){
		case MAIN:
			addDebug("MAIN -->");
			if(tab == null){
				http[MAIN].setURL(0, MAIN, "/?ctrl=ListGameStore");
				break;
			}
			int perpage = (inH - list.getTop())/ (HEI + DY) + 1;
			if(perpage < PER_PAGE) perpage = PER_PAGE;
			if(isSearching){ // search.........
				if(totalGameSearch > 0 && vec.size() >= totalGameSearch){ isLoading = false; return;}
				page = vecSearch.size()/perpage + 1;
				list.showLoading();
				http[SEARCHING].setURL(vecSearch.size(), SEARCHING, "/?ctrl=ListGameStore&key="+URLEncode(tsearch.getText().trim())+"&page="+page+"&perpage="+perpage);
			} else { // Category.....
				addDebug("TGame="+totalGame+" Vsize()="+vec.size());
				if(totalGame > 0 && vec.size() >= totalGame){ isLoading = false; return;}
				page = vecMain.size()/perpage + 1;
				list.showLoading();
				addDebug("param="+((iTabfocus<<16)|vec.size()));
				http[MAIN].setURL((iTabfocus<<16)|vec.size() ,MAIN, "/?ctrl=ListGameStore&cid="+tab[iTabfocus][0]+"&page="+page+"&perpage="+perpage);
			}
			break;
		case HIGHSCORE: //mid=<mid>&id=<id2>
			addDebug("HIGHSCORE " + index);
			hs = null;
			http[HIGHSCORE].setURL(index, HIGHSCORE, ((Info)vec.elementAt(index)).urlHighScore);
			break;
		case DETAIL: //mid=<mid>
			addDebug("DETAIL " + index);
			dt.reset();
			http[DETAIL].setURL(index, DETAIL, dt.info.urlDetail);
			break;
		case DOWNLOAD: //mid=<mid>&id=<id1>
			addDebug("DOWNLOAD " + index);
			dl.DauSo = dl.CuPhap = dl.note = "";
			http[DOWNLOAD].setURL(index, DOWNLOAD, ((Info)vec.elementAt(index)).urlDownload);
			break;
		}
	}
	public void getData(short stateID ,String dataget){
//		addDebug("data="+dataget);
		
//		if(this.state == stateID){
//			int id = http[stateID].param; 
//			if( != )
//				return;
//		}
		
		if(dataget == null) {
			addDebug("NULLLLLLLLLLL roai!");
			if(list.isLoading) list.hideLoading();
			if(dt.desc!= null && dt.desc.length() == 0) dt.index = -1;
			if(dl.DauSo!=null && dl.DauSo.length() == 0) dl.index = -1;
			else if(stateID == MAIN || stateID == SEARCHING){
				if(!isSearching) strWarning = (GLives.isTouchable ? "Chạm vào" : "Chọn") + " TAB để load lại...";
			}
			isLoading = false;
			return;
		}

		if(dataget.substring(0, 2).equals("R:")){
			String srr = dataget.substring(2);
			System.out.println(srr);
			switch(stateID){
			case MAIN:
			case SEARCHING:
				if(isSearching){
					totalGameSearch = 0;
					if(GLives.ScreenWidth <= 220)
						strWarning = srr;//"Không có kết quả phù hợp";
					else
						strWarning = srr;//"Không tìm thấy kết quả phù hợp";
					strSearch = ". . .";
				}
				else {
					totalGame = 0;
					strWarning = srr;//"Chưa có nội dung";
				}
				
				if(list.isLoading) list.hideLoading();
				registerTouch();
				break;	
			case HIGHSCORE:
				strWarning = srr;//"...danh sách rỗng...";
				break;
			default:
				strWarning = srr;
				break;
			}
			arrWar = GLives.ins.bmf_normal.splitStrInLine(strWarning, inW - 5*KC);
			if(state != MAIN && state != DOWNLOAD) list.getTo(0, 0);
			isLoading = false;
			return;
		}
		
		if(!dataget.substring(0, 2).equals("M:")){
			int p = dataget.indexOf(' ');
			dataget = dataget.substring(p + 1);
		}
		
		switch(stateID){
		case MAIN:
		case SEARCHING:
		{
			if(tab == null){
				String ar1[] = Static.split(dataget, "" + (char)21);
				tab = new String[ar1.length][3];
				for(int i = 0; i < ar1.length; i++){
					int coma = ar1[i].indexOf((char)20);
					tab[i][0] = ar1[i].substring(0, coma);
					tab[i][1] = ar1[i].substring(coma+1);
					tab[i][2] = GLives.ins.bmf_normal.stringFixEtc(ar1[i].substring(coma+1), wTab - 12);
				}
				addDebug("----> sau khi load TAB xong");
				sendRequest(MAIN, 1);
				return;
			}

			try{
			int dot = dataget.lastIndexOf('\n');
			if(dot == -1) break;
			
			//String sa[] = Static.split(dataget,"\r\n");
			int n = Integer.parseInt(dataget.substring(dot + 1).trim());
			if(isSearching){
				totalGameSearch = n;
				String sprefx;
				if(GLives.ScreenWidth <= 220)
					sprefx = "Có " + totalGameSearch + " kết quả cho \"";
				else
					sprefx = "Có " + totalGameSearch + " kết quả được tìm thấy cho \"";
				String sCut = GLives.ins.bmf_normal.stringFix(tsearch.getText(), inW - 30 - GLives.ins.bmf_normal.stringWidth(sprefx));
				strSearch = sprefx + sCut.substring(1) + (sCut.charAt(0) == '1' ? "...\"" : "\"");

			} else totalGame = n;
			String sg[] = Static.split(dataget.substring(0, dot - 1),"" + (char)21);
			
			for(int i = 0; i < sg.length; i++){
				String arr[] = Static.split(sg[i],"" + (char)20);
				
				Info in = new Info();
				in.name = arr[0];
				in.urlDetail = arr[1];
				in.urlDownload = arr[2].trim();
				in.urlHighScore = arr[3].trim();
				in.sub = arr[4]; 
				in.star = Integer.parseInt(arr[5]);
				in.wName = GLives.ins.bmf_bold.stringWidth(in.name);
				in.picon = arr[6]; in.icon = imgDefault;
				
				resizeSubText(in);
				
				if(stateID == SEARCHING) vecSearch.addElement(in);
				else vecMain.addElement(in);
				
				list.viewH += (HEI + DY);
			}
			
			if(list.isLoading) list.hideLoading();
			registerTouch();
			isLoading = false;
			sendIMGrequest(MAIN, 0);//iIMG_lst);
			} catch(Exception e){e.printStackTrace();}
			break;
		}
		case HIGHSCORE:
		{
			String o[] = Static.split(dataget, "" + (char)20);
			hs = new String[o.length][3];
			int dot = 0;
			for(int i = 1; i <= hs.length; i++){
				hs[i-1][0] = (i < 10 ? "000" : i < 100 ? "00" : i < 1000 ? "0" : "") + i;
				dot = o[i-1].indexOf(',');
				hs[i-1][1] = o[i-1].substring(0, dot);
				hs[i-1][2] = o[i-1].substring(dot+1);
			}
			correctHList(HIGHSCORE);
			break;
		}
		case DETAIL:
		{
			String _[] = Static.split(dataget, "" + (char)20);
			dt.info.nDownload = Integer.parseInt(_[0]);
			dt.desc = _[1];
			resizeDetailText();
			_[2] = _[2].trim();
			if(_[2].length() != 0){
				if(_[2].indexOf('|') == 0) _[2] = _[2].substring(1);
				if(_[2].lastIndexOf('|') == _[2].length()-1) _[2] = _[2].substring(0, _[2].length()-1);
				dt.pimg = Static.split(_[2], "|");
				if(dt.pimg.length > 0){
					dt.img = new Image[dt.pimg.length];
					for(int i = 0; i < dt.img.length; i++)
						dt.img[i] = imgDefault;
				}
				isLoading = false;
				sendIMGrequest(DETAIL, 0);
			}
			correctHList(DETAIL);
			break;
		}
		case DOWNLOAD:
		{
			//M:[cu phap]2[dau so]
			if(dataget.substring(0, 2).equals("M:")){
				int u = dataget.indexOf(20);
				dl.CuPhap = dataget.substring(2, u);
				dl.DauSo = dataget.substring(u+1);
			}
			addDebug("dl.DauSo="+dl.DauSo);
			break;
		}
		}
		
		if(state != MAIN && state != DOWNLOAD){
			list.getTo(0, 0);
		}
		isLoading = false;
	}
	
	private void sendSMS_toDownload(){
		if(dl.DauSo.length()==0){
			dlg.show("Server đang bận. Vui lòng chờ phản hồi...");
			return;
		}
		SMSSender.sendSMSToConfirmReward(dl.CuPhap, dl.DauSo , 
			new Event(){
				public void action() {
					dlg.show("Bạn đã gửi tin nhắn đến " + dl.DauSo + " thành công.");
				}
			},
			new Event(){
				public void action() {
					dlg.show("Gửi tin nhắn để download game không thành công.");
				}
			});
		
		changeSub(backState);
	}
	private boolean sendSMS_toGiveFriend(){
		String strNum = tnumber.getText().trim();
		if(strNum.length() < 10){
			dlg.show("Số điện thoại không đúng!\nPhải 10 hoặc 11 số và chỉ chấp nhận nhập ký số từ 0-9");
			return false;
		}
		if(dl.DauSo.length()==0){
			dlg.show("Server đang bận. Vui lòng chờ phản hồi...");
			return false;
		}
		SMSSender.sendSMSToConfirmReward(dl.CuPhap + " " + strNum , dl.DauSo , 
			new Event(){
				public void action() {
					dlg.show("Gửi ứng dụng đến thuê bao " + tnumber.getText().trim() + " thành công.");
				}
			},
			new Event(){
				public void action() {
					dlg.show("Không gửi được tin nhắn. Vui lòng kiểm tra lại.");
				}
			});
		
		changeSub(backState);
		return true;
	}
	
//	String db[] = {"","","","","","","","",""}; int idb = 0;
	private void addDebug(String str){
//		if(true){
//			if(idb < db.length - 1) idb++;
//			else{
//				for(int i = 0; i < db.length - 1; i++)
//					db[i] = db[i+1];
//			}
//			db[idb] = str;
//		} else 
//		{
//			System.out.println(str);
//		}
	}
//	private void drawDebug(Graphics g){
//		//g.setColor(0);
//		//g.fillRect(50, 100, 150, db.length*18);
//		g.setColor(0xFF0000);
//		for(int i = 0; i < db.length; i++)
//			g.drawString(db[i], 20, 100 + i*18, 0);
//	}
	
	class HTTP
	{
	private final short TEXT = 0;
	private final short IMAGE = 1;
	private short style;
	
	private String strURL[] = {"",""};
	private short type[] = {-1,-1};
	public int param[] = {-1,-1};
	Thread ConnectionThread = null;
	
	public boolean isWaiting = false;
	private boolean bStop = false;
	private InputStream iStrm = null;
	private HttpConnection conn = null;
	
	public void setURL(int pr, short typeData, String request){
		style = TEXT;
		
		if(checkURL(pr, typeData, "http://203.162.70.36/highscore" + request))
			doconnect();
		}
	public void setImageURL(short typeData, String url){
		style = IMAGE; 
		
		if(checkURL(-1, typeData, url))
			doconnect();
		}
	public boolean checkURL(int pr, short typeData, String request){
		int iPriority = 0;
		if(isWaiting){
			if(style == IMAGE)
				iPriority = 1;
			else if(!request.equals(strURL[0])){
				iPriority = 1;
				stop();
			} else return false;
		}
//		System.out.println(">>> " + request);
		type[iPriority] = typeData;
		param[iPriority] = pr;
		strURL[iPriority] = request;
		
		return (iPriority == 0);
		}
	public void cancel(){
		strURL[0] = strURL[1] = "";
		stop();
		}
	public void stop(){
		try {
			if(isWaiting){
				addDebug("-----------------> connect STOP");
				bStop = true;
				if (conn != null) {conn.close(); conn = null;}
	            if (iStrm != null) {iStrm.close(); iStrm = null;}
			}
		} catch (IOException e) {
			addDebug("Stop()-"+e.toString());
		}
		}
	private void doconnect(){
		(ConnectionThread= new Thread(){
			public synchronized void run() {
				while(strURL[0].length() > 0)
				{
					if(GLives.ins.currSlide.id != State.IGP) return;
					IGP igp = (IGP)GLives.ins.currSlide;
					byte data[] = null;
					
					isWaiting = true;
					try {
						addDebug("------> connect 0 - request " + type[0]);
						conn = (HttpConnection) Connector.open(strURL[0],Connector.READ);
						conn.setRequestProperty("User-Agent", "J2ME;"+GConfig.MaGame+"-"+GLives.ins.version+ ";" + GLives.ins.Partner); //  J2ME;mã game - version
						addDebug("-------> connect 1 :" + "J2ME;"+GConfig.MaGame+"-"+GLives.ins.version + ":");
						
						if(conn == null || bStop) {isWaiting = false; bStop = false; return;}
						
						// ??? always stop here!
				        if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
				        	iStrm = conn.openInputStream();
				        	addDebug("--------> connect 2");
				        	ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
				        	
				        	if(iStrm == null || bStop) {isWaiting = false; bStop = false; return;}
							
				        	int ch;
							while ((ch = iStrm.read()) != -1)
								bStrm.write(ch);
							
							if(iStrm == null || bStop) {isWaiting = false; bStop = false; return;}
	//						
							addDebug("----> connect 3");
							data = bStrm.toByteArray();
							bStrm.close();
							
							if(iStrm == null || bStop) {isWaiting = false; bStop = false; return;}
				        }
						else if (conn.getResponseCode() == HttpConnection.HTTP_NOT_FOUND) {
							connectFail("Yêu cầu không xác thực!");
			            } else {
			            	connectFail("Máy chủ đang rất bận hoặc không sẵn sàng. Vui lòng thử lại sau!");
			            }
					}
				    catch (SecurityException se) {
				    	connectFail("Không thể kết nối!\nBạn cần cho phép ứng dụng này được phép truy cập mạng!");
				    } catch (IOException ioex) {
				    	connectFail("Lỗi truy cập! Vui lòng thử lại sau!");// +"\n"+ioex.toString() + "====");
				    } catch (Exception e){
				    	isWaiting = false;
				    	bStop = false;
				    	addDebug("HTTP Trigger Error: " + e.toString());
				    	//connectFail("Lỗi truy cập! Vui lòng kiểm tra lại kết nối WIFI, GPRS.");
				    }
				    finally{
				        try {
				            if (iStrm != null) iStrm.close();
				            if (conn != null) conn.close();
				        } catch (IOException ioexception) {
				        	System.out.println("HTTTP Error: Huy khong duoc!");
				        }
			        	iStrm =null;
			            conn =null;
			            
			            // return result
			            if(data != null){
			            	addDebug(">>>> Nhan Data");
			            	
			            	if(style == TEXT)
			            		try {
			            			igp.getData(type[0], new String(data,"UTF-8"));
			            		} catch (UnsupportedEncodingException e) {
			            			e.printStackTrace();
			            		}
			            	else if(style == IMAGE)
			            		igp.getImageData(type[0], data);
			            }
			            
			            if(strURL[1].length() > 0){
			            	type[0] = type[1];
			            	param[0] = param[1];
			            	strURL[0] = strURL[1];
			            	
			            	strURL[1] = "";
			            } else {
			            	strURL[0] = "";
			            	//ConnectionThread = null;
			            	addDebug(">>> Finish HTTP!");
			            }
			            
			    		isWaiting = false;
			    		bStop = false;
				    }
				}
			}
		}).start();
		}
	private void connectFail(String exp){
		if(style == IMAGE) ;//dlg.show("Có lỗi truy xuất mạng.\nHình ảnh sẽ không được nạp tiếp");
		else dlg.show_static(exp);
		if(GLives.ins.currSlide.id == State.IGP){
			IGP igp = (IGP)GLives.ins.currSlide;
			if(style == TEXT) igp.getData(type[0], null);
			//else if(style == IMAGE) igp.getImageData(type, null);
		}
		isWaiting = false;
		bStop = false;
		}
	}
	
	class Dialog
	{
	public int iFrameCnt = 0;
	private int x, y, w, h;
	private String text; private String arrT[];
	public void show(String content){
		text=content;
		iFrameCnt = 50;
		rezise();
		}
	public void show_static(String content){
		show(content);
		iFrameCnt=-1;
		}
	public void hide(){
		iFrameCnt = 0;
		}
	public void update(){
		if(iFrameCnt > 0)
			iFrameCnt--;
		}
	public void drawMe(Graphics g){
		if(iFrameCnt==0 || arrT == null) return;
		g.setClip(inX, inY, inW, inH);
		paintBFrame(g, dlg.x, dlg.y, dlg.w, dlg.h, imgDialog, 18, 16, 11, 9, 20, 70, 16, 20, true);
		for(int i = 0; i < arrT.length; i++)
			drawString(g, arrT[i], GLives.ScreenWidth>>1, dlg.y + 13 + HDESCTEXT*i, 2, 0x003300);
		}
	public void rezise(){
		if(iFrameCnt==0 || text == null || text.length() == 0) return;
		w = inW - 50;
		arrT = GLives.ins.bmf_normal.splitStrInLine(text, w - 10);
		h = arrT.length*18 + 20;
		x = (GLives.ScreenWidth - w)>>1;
		y = GLives.ScreenHeight - inY - h - 70;
		}
	}
}
